/* lifeprog.c a demo for lino */
#include "lino.h"
#include "lifeprog.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
char state[EDGE+2][EDGE+2];
char newstate[EDGE][EDGE];
char trans[10]={0,0,0,1,1,1,0,0,0,0};
FILE* logfile;
main(int argc, char ** argv)
{
   int i,j,count;
   char logfilename[80];
   sprintf(logfilename,"logf%s_%s.txt",argv[1],argv[2]);
   fprintf(stderr,"%s\n",logfilename);
   logfile=fopen(logfilename,"w");
   for(i=0;i<EDGE+2;i++)
	for(j=0;j<EDGE+2;j++)state[i][j]=(i<j?1:0);
   for(count=0;count<600;count++)
   {
	writestates();
	readstates();
        exchangecorners();
        for(i=1;i<=EDGE ;i++){
	 for (j=0;j<=EDGE+1 ;j++)
	  fprintf(logfile,"%c",'0'+state[i][j]);
	 fprintf(logfile,"\n");
        }
        fprintf(logfile,"run %d\n",count);

	updatestates();

   }
   fclose(logfile);
   close(NORTHOUT );
   close(EASTOUT );
   close( SOUTHOUT );
   close( WESTOUT );
}

updatestates()
{
	int i,j;
	for(i=0;i<EDGE;i++)
	for(j=0;j<EDGE;j++){
		int k,l,t=0;
	        for(k=0;k<=2;k++)for (l=0;l<=2;l++) t+=state[i+k][j+l];
		newstate[i][j]=trans[t];
        }
	for(i=0;i<EDGE;i++)
	for(j=0;j<EDGE;j++)state[i+1][j+1]=newstate[i][j];
}
writestates()
{
	char westbuf[EDGE];char eastbuf[EDGE];int i;
	write( NORTHOUT, &(state[1][1]),EDGE);
	write( SOUTHOUT , &(state[EDGE][1]),EDGE);
	for(i=0;i<EDGE;i++){westbuf[i]=(state[i+1][1])&1;eastbuf[i]= (state[i+1][EDGE])&1  ;}
	write( EASTOUT,eastbuf,EDGE);
	write( WESTOUT, westbuf,EDGE);
}
exchangecorners()
{       /* simple i/o on cardinal points of compas leaves diagonal corners unfilled we need a second phase to handle these */
	write(&state[1][0],NORTHOUT,1);write(&state[1][1+EDGE],NORTHOUT,1);
        write(&state[0][EDGE],EASTOUT,1);write(&state[1+EDGE][EDGE],EASTOUT,1);
        write(&state[EDGE][0],SOUTHOUT,1);write(&state[EDGE][1+EDGE],SOUTHOUT,1);
        write(&state[0][1],WESTOUT,1);write(&state[0][EDGE],WESTOUT,1);

	read(&state[0][1+EDGE],EASTIN,1);read(&state[1+EDGE][1+EDGE],EASTIN,1);
	read(&state[0][0],NORTHIN,1);read(&state[0][1+EDGE],NORTHIN,1);
	read(&state[0][0],WESTIN,1);read(&state[1+EDGE][0],WESTIN,1);
	read(&state[1+EDGE][0],SOUTHIN,1);read(&state[1+EDGE][1+EDGE],SOUTHIN,1);
}
readstates()
{
	char westbuf[EDGE];char eastbuf[EDGE];int i;
	i=read( NORTHIN, &(state[0][1]), EDGE );
	i+=read( SOUTHIN, &(state[EDGE+1][1]),EDGE);
	i+=read(  EASTIN,eastbuf,EDGE);
	i+=read( WESTIN, westbuf,EDGE);
        if(i<EDGE*4) fprintf(stderr," only read %d \n",i);
	for(i=0;i<EDGE;i++){state[i+1][0]=westbuf[i];state[1+i][EDGE+1]=eastbuf[i] ;}

}
